const STORAGE_PREFIX = import.meta.env.VITE_STORAGE_PREFIX

/**
 * @description: sessionStorage部分操作
 */

function createSessionStorage() {
  function set(key) {
    const json = JSON.stringify(value)
    window.sessionStorage.setItem(`${STORAGE_PREFIX}${String(key)}`, json)
  }

  function get(key) {
    const json = sessionStorage.getItem(`${STORAGE_PREFIX}${String(key)}`)
    if (!json)
      return null

    const storageData = JSON.parse(json)

    if (storageData)
      return storageData

    return null
  }

  function remove(key) {
    window.sessionStorage.removeItem(`${STORAGE_PREFIX}${String(key)}`)
  }

  const clear = window.sessionStorage.clear

  return {
    set,
    get,
    remove,
    clear,
  }
}

export const session = createSessionStorage()

/**
 * @description: 本地存储工具类
 */
class Storage {
  /**
   * @description: 获取本地存储
   * @param {string} key - 存储键名
   * @param {any} defaultValue - 默认值
   * @return {any} - 返回存储值或默认值
   */
  get(key, defaultValue = null) {
    try {
      const value = localStorage.getItem(key)
      return value ? JSON.parse(value) : defaultValue
    } catch (error) {
      console.error(`获取本地存储失败: ${key}`, error)
      return defaultValue
    }
  }

  /**
   * @description: 设置本地存储
   * @param {string} key - 存储键名
   * @param {any} value - 存储值
   */
  set(key, value) {
    try {
      localStorage.setItem(key, JSON.stringify(value))
    } catch (error) {
      console.error(`设置本地存储失败: ${key}`, error)
    }
  }

  /**
   * @description: 删除本地存储
   * @param {string} key - 存储键名
   */
  remove(key) {
    try {
      localStorage.removeItem(key)
    } catch (error) {
      console.error(`删除本地存储失败: ${key}`, error)
    }
  }

  /**
   * @description: 清空本地存储
   */
  clear() {
    try {
      localStorage.clear()
    } catch (error) {
      console.error('清空本地存储失败', error)
    }
  }
}

export const storage = new Storage()